package com.atguigu.gmall.pms.config;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.consts.GmallConsts;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class RabbitmqConfig {
    @Resource
    RabbitTemplate rabbitTemplate;

    public static RabbitmqConfig rabbitmqConfig;
    @PostConstruct
    public void init(){
        //http://search.gmall.com/search?keyword=%E5%B0%8F%E7%B1%B3
        // UrlEncode+UrlDecode
        // 以后项目中多端交互时 如果有乱码问题 可以通过base64转码传递数据
        rabbitTemplate.setReturnCallback(( message,  replyCode,  replyText,  exchange,  routingKey)->{
            log.error("消息未到达队列：messageTag = {} ,body = {} ,  replyCode = {} , " +
                    "   replyText = {} , exchange = {} , routingKey = {}",
                       message.getMessageProperties().getDeliveryTag(),
                    Base64.getEncoder().encode(message.getBody()),
                            replyCode,replyText , exchange , routingKey
                    );
        });
        rabbitTemplate.setConfirmCallback((  correlationData,  ack,  cause)->{
            if(!ack){
                log.error("消息未到达交换机：cause = {}" , cause);
            }
        });
        rabbitmqConfig = this;
    }


    public void sendSearchMsg(Object param,Integer type) {
        Map<String,Object> map = new HashMap<>();
        map.put("type", type);//2表示新增
        map.put("token" , IdWorker.getIdStr());// token用来解决幂等性问题
        map.put("param",param); //消息的真实内容
        rabbitTemplate.convertAndSend(GmallConsts.SEARCH_EXCHANG,
                GmallConsts.SEARCH_ROUTING_KEY,
                map);
    }
}
